#!/usr/bin/env python
# -*- coding: utf-8 -*-
import yaml


def node_select(node, path, default=None):
    """ node_select(node, path) -> value from node at matching path.

    This function currently only supports absolute paths.  It would be
    nice if we supported paths similar to XPath
    (http://www.w3.org/TR/xpath).
    """
    if not path:
        return
    part = path[0]
    last = len(path) == 1
    if isinstance(node, (tuple, list)) and isinstance(part, (int, long, slice)):
        try:
            item = node[part]
            return item if last else node_select(item, path[1:], default)
        except (IndexError, ):
            return default        
    elif isinstance(node, (dict, )):
        try:
            item = node[part]
            return item if last else node_select(item, path[1:], default)
        except (KeyError, ):
            return default
    return default


def node_set(node, path, value):
    if not path or not isinstance(node, (list, dict)):
        return
    part = path[0]
    last = len(path) == 1
    if last:
        node[part] = value
    else:
        try:
            next = node[part]
        except (KeyError, ):
            if isinstance(part, (int, long)):
                next = node[part] = []
            else:
                next = node[part] = {}
        node_set(next, path[1:], value)


yaml_dump = yaml.dump
yaml_dump_all = yaml.dump_all

yaml_load = yaml.load
yaml_load_all = yaml.load_all
